package com.fang.security.security.handler;

import com.alibaba.fastjson.JSON;
import com.fang.security.common.CommonConstants;
import com.fang.security.common.base.ServiceCode;
import com.fang.security.common.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description 登录失败处理器
 * @Author Bernie
 * @Date 2024/4/23 10:45
 **/
@Slf4j
@Component
public class CustomizeAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        //返回json数据
        JsonResult result = null;
        if (e instanceof AccountExpiredException) {
            log.error("onAuthenticationFailure账号过期，AccountExpiredException===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.USER_ACCOUNT_UNAVAILABLE);
        } else if (e instanceof BadCredentialsException) {
            log.error("onAuthenticationFailure密码错误，BadCredentialsException===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.USER_PASSWORD_ERROR);
        } else if (e instanceof CredentialsExpiredException) {
            log.error("onAuthenticationFailure密码过期，CredentialsExpiredException===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.USER_PASSWORD_EXPIRED);
        } else if (e instanceof DisabledException) {
            log.error("onAuthenticationFailure账号不可用，DisabledException===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.USER_ACCOUNT_UNAVAILABLE);
        } else if (e instanceof LockedException) {
            log.error("onAuthenticationFailure账号锁定，LockedException===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.ACCOUNT_LOCKED);
        } else if (e instanceof InternalAuthenticationServiceException) {
            log.error("onAuthenticationFailure账号不存在，InternalAuthenticationServiceException===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.ACCOUNT_NOT_EXIST);
        } else {
            log.error("onAuthenticationFailure其他错误，e ===========>{}", e.getMessage());
            result = JsonResult.fail(ServiceCode.SYSTEM_BUSY);
        }
        httpServletResponse.setContentType(CommonConstants.CommonResponse.JSON_U8_CONTENT_TYPE);
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
